<template>
  <div class="register-container">
    <!-- 背景装饰元素 -->
    <div class="background-decoration">
      <!-- 精美的动态背景 -->
      <div class="dynamic-background">
        <div class="building building-1"></div>
        <div class="building building-2"></div>
        <div class="building building-3"></div>
        <div class="building building-4"></div>
        <div class="building building-5"></div>
        <div class="cloud cloud-1"></div>
        <div class="cloud cloud-2"></div>
        <div class="cloud cloud-3"></div>
        <div class="sun"></div>
        <div class="light-ray ray-1"></div>
        <div class="light-ray ray-2"></div>
        <div class="light-ray ray-3"></div>
      </div>

      <!-- 浮动装饰元素 -->
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
      <div class="floating-shape shape-5"></div>
      <div class="floating-shape shape-6"></div>
    </div>

    <div class="register-wrapper">
      <!-- 左侧装饰面板 -->
      <div class="decorative-panel">
        <div class="panel-content">
          <div class="logo-section">
            <div class="main-logo">
              <svg viewBox="0 0 100 100" class="logo-svg">
                <circle cx="50" cy="50" r="45" fill="none" stroke="#4A90E2" stroke-width="2"/>
                <circle cx="50" cy="50" r="35" fill="none" stroke="#FF6B6B" stroke-width="2"/>
                <circle cx="50" cy="50" r="25" fill="none" stroke="#50E3C2" stroke-width="2"/>
                <circle cx="50" cy="50" r="15" fill="#4A90E2"/>
              </svg>
            </div>
            <h1 class="app-title">HousingHub</h1>
            <p class="app-subtitle">现代住房租赁平台</p>
          </div>

          <div class="features-section">
            <div class="feature-item">
              <div class="feature-icon">
                <!-- 海量房源图标 -->
                <svg class="feature-svg" viewBox="0 0 24 24">
                  <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
                </svg>
              </div>
              <div class="feature-text">
                <h3>海量房源</h3>
                <p>覆盖全国多个城市，数百万套房源供您选择</p>
              </div>
            </div>

            <div class="feature-item">
              <div class="feature-icon">
                <!-- 真实可靠图标 -->
                <svg class="feature-svg" viewBox="0 0 24 24">
                  <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/>
                </svg>
              </div>
              <div class="feature-text">
                <h3>真实可靠</h3>
                <p>严格审核房源信息，保障您的权益</p>
              </div>
            </div>

            <div class="feature-item">
              <div class="feature-icon">
                <!-- 贴心服务图标 -->
                <svg class="feature-svg" viewBox="0 0 24 24">
                  <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"/>
                </svg>
              </div>
              <div class="feature-text">
                <h3>贴心服务</h3>
                <p>专业客服团队，为您提供全程服务</p>
              </div>
            </div>
          </div>

          <div class="quote-section">
            <p class="quote-text">"找到理想的家，从 HousingHub 开始"</p>
            <p class="quote-author">—— HousingHub 团队</p>
          </div>
        </div>
      </div>

      <!-- 注册表单区域 -->
      <div class="register-box">
        <div class="form-header">
          <h2>创建账户</h2>
          <p>注册新用户</p>
        </div>

        <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
            label-position="left"
            label-width="0px"
        >
          <el-form-item prop="username">
            <el-input
                v-model="registerForm.username"
                prefix-icon="el-icon-user"
                placeholder="用户名"
                class="custom-input"
            />
          </el-form-item>

          <el-form-item prop="email">
            <el-input
                v-model="registerForm.email"
                prefix-icon="el-icon-message"
                placeholder="QQ邮箱"
                class="custom-input"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="registerForm.password"
                prefix-icon="el-icon-lock"
                :type="showPassword ? 'text' : 'password'"
                placeholder="密码"
                class="custom-input"
                show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
                v-model="registerForm.confirmPassword"
                prefix-icon="el-icon-lock"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="确认密码"
                class="custom-input"
                show-password
            />
          </el-form-item>

          <el-form-item prop="verifyCode" class="verify-code-item">
            <div class="verify-code-container">
              <el-input
                  v-model="registerForm.verifyCode"
                  prefix-icon="el-icon-key"
                  placeholder="验证码"
                  class="custom-input verify-input"
              />
              <el-button
                  :disabled="countdown > 0"
                  @click="getVerifyCode"
                  class="verify-code-btn"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                :loading="registerLoading"
                @click="handleRegister"
                class="register-btn custom-button"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-link">
          <p>已有账户？<el-link type="primary" @click="goToLogin">立即登录</el-link></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { userRegister, sendRegisterCode } from '@/utils/apiService'

const router = useRouter()

// 表单引用
const registerFormRef = ref(null)

// 倒计时
const countdown = ref(0)

// 密码显示状态
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 表单数据
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verifyCode: ''
})

// 表单验证规则
const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入QQ邮箱', trigger: 'blur' },
    { pattern: /^[1-9]\d{4,10}@qq\.com$/, message: '请输入正确的QQ邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
      message: '密码必须包含字母、数字和特殊字符，且长度至少为8位，不能包含空格',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
})

// 状态
const registerLoading = ref(false)

// 获取验证码
const getVerifyCode = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请先输入QQ邮箱')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[1-9]\d{4,10}@qq\.com$/
  if (!emailRegex.test(registerForm.email)) {
    ElMessage.warning('请输入正确的QQ邮箱')
    return
  }

  try {
    console.log(`向后端发送请求: 获取验证码 - 邮箱: ${registerForm.email}`)

    // 调用发送验证码API
    const response = await sendRegisterCode(registerForm.email)

    console.log('🔍 验证码发送响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)

      ElMessage.success('验证码已发送，请注意查收')
    } else {
      console.log('❌ 验证码发送失败:', responseData)
      ElMessage.error(responseData.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('验证码发送失败，请检查网络连接')
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) {
      ElMessage.warning('请检查并完善注册信息')
      return
    }

    registerLoading.value = true

    // 准备注册数据
    const registerData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      confirmPassword: registerForm.confirmPassword,
      verificationCode: registerForm.verifyCode
    }

    console.log('向后端发送注册请求:', registerData)

    // 调用注册API
    const response = await userRegister(registerData)

    console.log('🔍 注册响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === '200' || responseData.code === 200) {
      ElMessage.success('注册成功！请登录')

      // 清空表单
      Object.keys(registerForm).forEach(key => {
        registerForm[key] = ''
      })

      // 跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      console.log('❌ 注册失败:', responseData)
      ElMessage.error(responseData.message || '注册失败')
    }
  } catch (error) {
    console.error('注册错误:', error)

    // 根据错误类型显示不同的提示
    if (error.response && error.response.status === 400) {
      ElMessage.error('注册信息有误，请检查后重试')
    } else if (error.response && error.response.status === 409) {
      ElMessage.error('用户名或邮箱已存在')
    } else {
      ElMessage.error('注册失败，请检查网络连接或联系管理员')
    }
  } finally {
    registerLoading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  padding: 20px;
  background: linear-gradient(135deg, #1a2a6c, #2c3e50);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.register-wrapper {
  display: flex;
  width: 900px;
  height: 550px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
  z-index: 1;
  animation: fadeIn 0.8s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.decorative-panel {
  flex: 1;
  background: linear-gradient(135deg, rgba(74, 144, 226, 0.85) 0%, rgba(80, 227, 194, 0.85) 100%);
  color: white;
  padding: 40px;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.decorative-panel::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transform: rotate(45deg);
  animation: shine 5s infinite;
}

@keyframes shine {
  0% {
    transform: rotate(45deg) translateX(-100%);
  }
  100% {
    transform: rotate(45deg) translateX(100%);
  }
}

.panel-content {
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
}

.main-logo {
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.logo-svg {
  width: 100%;
  height: 100%;
}

.app-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.app-subtitle {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
}

.features-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.feature-item {
  display: flex;
  gap: 15px;
  align-items: flex-start;
}

.feature-icon {
  font-size: 24px;
  background: rgba(255, 255, 255, 0.2);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  animation: iconFloat 3s infinite ease-in-out;
}

@keyframes iconFloat {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

/* 功能图标样式 */
.feature-svg {
  width: 24px;
  height: 24px;
  fill: white;
}

.feature-text h3 {
  margin: 0 0 5px;
  font-size: 18px;
  font-weight: 600;
  /* 修复"海量房源"没有对齐的问题 */
  text-align: left;
}

.feature-text p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
  text-align: left;
}

.quote-section {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
}

.quote-text {
  font-style: italic;
  margin: 0 0 10px;
  font-size: 16px;
}

.quote-author {
  margin: 0;
  font-size: 14px;
  opacity: 0.8;
}

.register-box {
  width: 380px;
  background: rgba(240, 244, 248, 0.95);
  backdrop-filter: blur(10px);
  padding: 30px;
  display: flex;
  flex-direction: column;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0 0 10px;
  font-weight: 700;
}

.form-header p {
  color: #7f8c8d;
  margin: 0;
  font-size: 16px;
}

.register-form {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.verify-code-item {
  margin-bottom: 15px !important;
}

.verify-code-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.verify-input {
  flex: 1;
}

.verify-code-btn {
  padding: 12px 10px;
  font-size: 12px;
  border-radius: 8px;
  background: #4A90E2;
  color: white;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.verify-code-btn:hover {
  background: #3a7bc8;
}

.verify-code-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.custom-input :deep(.el-input__inner) {
  padding: 15px;
  border-radius: 10px;
  /* 移除外边框，只保留内圆角矩形 */
  border: none;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.custom-input :deep(.el-input__inner):focus {
  outline: none;
  box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3);
}

.custom-button {
  padding: 15px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
  width: 100%;
  margin-bottom: 15px;
}

.register-btn {
  background: linear-gradient(135deg, #FF6B6B 0%, #FFA500 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
}

.register-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 20px rgba(255, 107, 107, 0.5);
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #7f8c8d;
  font-size: 14px;
}

.login-link a {
  cursor: pointer;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__error) {
  padding-top: 2px;
}

@media (max-width: 992px) {
  .register-wrapper {
    width: 95%;
    max-width: 500px;
    height: auto;
  }

  .decorative-panel {
    display: none;
  }

  .register-box {
    width: 100%;
  }
}
</style>
